package HashTablePackage;

import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Lzm
 * @version 1.0
 */
public class fourSumCount_ {
  @Test
  public void fourSumCountTest(){
    int[] nums1 = new int[]{1,2};
    int[] nums2 = new int[]{-2,-1};
    int[] nums3 = new int[]{-1,2};
    int[] nums4 = new int[]{0,2};
    System.out.println(fourSumCount(nums1,nums2,nums3,nums4));
  }

  /*public static int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4){
    int count = 0 ;
    if (nums1.length == 0 || nums2.length == 0 || nums3.length == 0 || nums4.length == 0 ){
      return 0;
    }
    Map<String ,Integer> map1 = new HashMap<>();
    for (int num1 : nums1) {
      for (int num2 : nums2) {
        if (map1.containsKey(num2 + num1 + "")){
          Integer value = map1.get(num2 + num1 + "");
          map1.put(num2 + num1 + "",value + 1);
        }
        else{
          map1.put(num2 + num1 + "",1);
        }
      }
    }
    for (int num3 : nums3) {
      for (int num4 : nums4) {
        int target = 0 - (num3 + num4);
        if (map1.containsKey(target + "")){
          count += map1.get(target + "");
        }
      }
    }
    return count;
  }*/

  public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
    if (nums1.length == 0 || nums2.length == 0 || nums3.length == 0 || nums4.length == 0 ){
      return 0;
    }
    int count = 0;
    /*将nums1 + nums2的得数放到map中*/
    Map<String,Integer> map = new HashMap<>();
    for (int num1 : nums1) {
      for (int num2 : nums2) {
        /*如果map中已经存在了nums1 + nums2这个key, 那令其对应的value + 1*/
        if (map.containsKey(num1 + num2 + "")){
          Integer value = map.get(num1 + num2 + "") + 1;
          map.put(num1 + num2 + "",value);
        }
        else{
          map.put(num1 + num2 + "",1);
        }
      }
    }
    for (int num3 : nums3) {
      for (int num4: nums4) {
        int newTarget = 0 - num3 - num4;
        if (map.containsKey(0 - num3 - num4 + "")){
          count += map.get(0 - num3 - num4 + "");
        }
      }
    }
    return count;
  }
}
